#-------------------------------------------------------------------------------
# Name:        Version Check
# Purpose:
#
# Author:      Pablo
#
# Created:     09/01/2013
# Copyright:   (c) Monxcleyr Productions 2013
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import urllib2, io, logging, pygame
from ..game import config
from ..gui import label

class VersionCheck():

  """Will check current game version against website and prompt user to update, if needed"""

  def __init__(self):
    self.uptodate = 0
    self.info = {}
    try:
      self.versionconfig = urllib2.urlopen('http://monxcleyr.tk/versions/versions.ini')
##      print self.versionconfig.read()
    except:
      self.uptodate = 1
      logging.warning('Syncing to Monxcleyr Version Checking Service failed')
      self.versionconfig = None

    self.conf = config.Config()
    if self.versionconfig != None:
      try:
        self.conf.readfp(io.BytesIO(self.versionconfig.read()))
      except:
        self.uptodate = 1
        logging.warning('Syncing to Monxcleyr Version Checking Service failed')
        self.versionconfig = None

    self.info['up-to-date'] = bool(self.uptodate)



  def check(self, name, version):
    self.version = version
    if self.versionconfig == None:
      return None
    try:
      confversion = self.conf.get(name, 'version')
      self.confversion = confversion
      if confversion == version:
        logging.info('%s is up-to-date.' % name)
        self.uptodate = 1
      else:
        logging.info('There is a new version of %s avaliable. Download at %s' % (name, self.conf.get(name, 'link')))
        self.uptodate = 0
      self.info['link'] = self.conf.get(name, 'link')
      self.info['updateversion'] = confversion
    except:
      logging.info('%s is not monitored by Monxcleyr Version Checking Service' % name)
      self.uptodate = 1

    self.info['up-to-date'] = bool(self.uptodate)

  def draw(self, surface, pos):

    """ Draws a small text displaying the version and a notification if there is a new version avaliable. """


    self.font = pygame.font.Font('resources/fonts/system.ttf', 9)
    self.label = label.Label(surface, ' ', pos, 'left', self.font, (85,136,208))

    text = self.version

##    if self.uptodate:
##      text = self.version
##    else:
##      text = '%s | Version %s avaliable!' % (self.version, self.confversion)

    self.label.setText(text)
    self.label.draw()



